

from tkinter import *
import threading
import socket

PORT = 9991

m = ""
s = None

clients = []
# 处理其中一个客户端的输入内容
class MyThread2(threading.Thread):

    def __init__(self,conn,addr):
        threading.Thread.__init__(self)
        self.conn = conn
        self.addr = addr

    def run(self):
        global m
        while True:
            data = self.conn.recv(1024)
            if data:
                print(data)
                m += data.decode() + "\n"
                message.config(text=m)

                # 转发给所有客户端
                for i in range(len(clients)):
                    clients[i].send(data)

            else:
                break



# 处理用户连入
class MyThread(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ss.bind(("127.0.0.1", PORT))
        print(f"服务器已启动，监听{PORT}端口")
        ss.listen(5)
        global s
        while True:
            conn,addr = ss.accept()
            print("有客户端连入",conn,addr)
            clients.append(conn)

            s = conn
            # 新开线程处理该客户端的信息
            t2 = MyThread2(conn,addr)
            t2.start()

t1 = MyThread()
t1.start()

root = Tk()
root.title("服务器")
root.geometry("300x400")
message = Message(root,text="aaa\nbbb",width=200)
message.pack()

def send():
    s.send(entry.get().encode("utf-8"))


entry = Entry(root)
entry.pack()
button1 = Button(root,text="Send",command=send)
button1.pack()
button = Button(root,text="Exit",command=root.quit)
button.pack()

root.mainloop()